<template>
  <div class="app-container">
    <!-- <app-header> </app-header> -->
    <div class="app-main">
      <div class="progress-bar">
        <img src="@/assets/images/apply/progress-bar2.png" alt="" />
      </div>

      <label class="input-box">
        
        <span class="title">
          <!-- <span class="red-star">*</span> -->
          房屋所在地
        </span>
        <mt-field
          type="text"
          placeholder="请输入房屋所在地"
          :value="cityName"
          readonly
          disableClear
          class="input"
          v-hint-emoji
        ></mt-field>
      </label>
      <label class="input-box" @click.prevent="setPopupType('community')">
        <span class="title">
          <!-- <span class="red-star">*</span> -->
          小区名称</span>
        <mt-field
          type="text"
          placeholder="请选择小区名称"
          v-model="community.name"
          :disabled="true"
          class="input"
          v-hint-emoji
        >
          <img src="@/assets/images/common/arrow-right.png" class="arrow" />
        </mt-field>
      </label>
      <label class="input-box">
        <span class="title" >楼栋号</span>
        <mt-field
          type="text"
          placeholder="请输入楼栋号"
          v-model="building.name"
          class="input"
          v-hint-emoji
        >
          <img
            src="@/assets/images/common/arrow-right.png"
            class="arrow"
            v-show="community.name && community.id"
            @click.stop.prevent="setPopupType('building')"
          />
        </mt-field>
      </label>
      <!-- <label class="input-box">
        <span class="title">
          <span class="red-star">*</span>
          单元</span>
        <mt-field
          type="text"
          placeholder="请输入单元"
          v-model="unit.name"
          class="input"
          v-hint-emoji
        >
          <img
            src="@/assets/images/common/arrow-right.png"
            class="arrow"
            v-show="building.name && building.id"
            @click.stop.prevent="setPopupType('unit')"
          />
        </mt-field>
      </label> -->
      <label class="input-box">
        <span class="title" >门牌号</span>
        <mt-field
          type="text"
          placeholder="请输入门牌号"
          v-model="house.name"
          class="input"
          v-hint-emoji
        >
          <img
            src="@/assets/images/common/arrow-right.png"
            class="arrow"
            v-show="unit.name && unit.id"
            @click.stop.prevent="setPopupType('house')"
          />
        </mt-field>
      </label>
      <!-- <label class="input-box">
        <span class="title" style="text-indent:.15rem">总楼层数</span>
        <mt-field
          type="number"
          placeholder="请输入总楼层数"
          v-model.number="totalFloor"
          class="input"
        ></mt-field>
      </label>
      <label class="input-box">
        <span class="title" style="text-indent:.15rem">所在楼层</span>
        <mt-field
          type="number"
          placeholder="请输入所在楼层"
          v-model.number="floor"
          class="input"
        ></mt-field>
      </label> -->
      <label class="input-box">
        <span class="title">
          <!-- <span class="red-star">*</span> -->
          建筑面积</span>
        <mt-field
          type="number"
          placeholder="请输入建筑面积"
          v-model.number="buildingArea"
          class="input"
          >m²</mt-field
        >
      </label>
      <label class="input-box" @click="setPopupType('houseType')">
        <span class="title">
          <!-- <span class="red-star">*</span> -->
          房产类型</span>
        <mt-field
          type="text"
          placeholder="请选择房产类型"
          v-model="houseType"
          :attr="{ readonly: true }"
          class="input"
        >
          <img
            src="@/assets/images/common/arrow-right.png"
            class="arrow"
            @click.stop
          />
        </mt-field>
      </label>
      <div class="btns">
        <button
          class="btn btn-primary btn-apply"
          :disabled="btnDisable"
          @click="evaluate()"
        >
          在线评估
        </button>
      </div>
    </div>
    <mt-popup
      v-model="popupVisible"
      position="bottom"
      :modal="popupType === 'houseType' ? true : false"
      style="width:100%"
    >
      <mt-picker
        :showToolbar="true"
        v-if="popupType === 'houseType'"
        ref="picker"
        :slots="[
          {
            flex: 1,
            values: houseTypeEnum,
            className: 'slot1',
            textAlign: 'center'
          }
        ]"
        @change="onPickerValuesChange"
      >
        <div class="pickerToolBar">
          <button @click="togglePopup">取消</button>
          <span>请选择</span>
          <button @click="pickerConfirm()">确定</button>
        </div>
      </mt-picker>
      <div v-else class="search-wrapper">
        <!-- 遮盖层 -->
        <div class="search-header">
          
          <label class="input-box">
            <i class="icon search"></i>
            <mt-field
              type="text"
              placeholder="请输入关键字"
              v-model="searchKey"
              class="input"
            ></mt-field>
          </label>
          <button @click="togglePopup">返回</button>
        </div>
        <div class="search-content">
          <ul>
            <li
              :class="{ between: popupType === 'community' }"
              v-for="(item, index) in searchResult"
              :key="index"
              @click="
                searchResultClick(
                  item.residentialareaName || item.name,
                  item.communityID || item.GUID,
                  item.districtName
                )
              "
            >
              <span>{{ item.residentialareaName || item.name }}</span>
              <span>{{ item.districtName }}</span>
            </li>
          </ul>
        </div>
      </div>
    </mt-popup>
  </div>
</template>

<script>
import { FuZhou, HouseTypeEnum } from "@/utils/constant";
import { validSpecialChar } from "@/utils/validate";
import { debounce } from "@/utils";
import {
  matchCommunity,
  getBuildingUnit,
  buildingEvaluate
} from "@/api/customer";

/* 根据关键字查询匹配房产相关信息 */
function querySearchResult(newVal, oldVal) {
  if (this.popupType === "community") {
    /* 小区 */
    if (this.searchKey) {
      matchCommunity({
        cityCode: this.cityCode,
        communityName: this.searchKey.replace(/\s+/g, "") // 空格替换
      }).then(res => {
        if (res.respCode === "000000") {
          this.searchResult = res.params;
        }
      });
    } else {
      this.searchResult = [];
    }
  } else {
    /* 楼栋|单元|户号 */
    this.searchResult = matchSearchKey(this.buildingUnitResult, this.searchKey);
  }
}

/* 根据关键字过滤匹配*/
function matchSearchKey(origin, key) {
  if (!key) return origin;
  return origin.filter(item => item.name.includes(key));
}

export default {
  name: "apply2",
  data() {
    return {
      cityCode: FuZhou.cityCode, //城市编码(目前固定写死)
      cityName: FuZhou.cityName,
      districtName: "", // 区名
      community: {
        name: "", //小区名称
        id: "" //小区GUID
      },
      building: {
        name: "", //楼栋名称
        id: "" //楼栋GUID
      },
      unit: {
        name: "", //单元名称
        id: "" //单元GUID
      },
      house: {
        name: "", //户号名称
        id: "" //户号GUID
      },
      totalFloor: "", //总楼层
      floor: "", //所在层
      buildingArea: "", //建筑面积(必须大于0)
      houseType: "住宅", //房产类型（枚举：住宅、别墅)
      houseTypeEnum: HouseTypeEnum,
      popupVisible: false,
      popupType: "", // popup弹出类型
      searchKey: "", //搜索关键字
      searchResult: [], //搜索结果
      buildingUnitResult: [] //（楼栋|单元|户号）查询结果
    };
  },
  computed: {
    btnDisable() {
      return !(
        this.cityCode &&
        this.buildingArea &&
        this.houseType &&
        this.house.name &&
        (this.community.id && this.community.name) &&
        //  ||
        this.building.name
        // this.totalFloor ||
        // this.floor  ||
        // this.unit.name 
      );
    }
  },
  watch: {
    searchKey: debounce(querySearchResult, 350),
    community: {
      handler() {
        this.building.name = this.building.id = "";
        this.unit.name = this.unit.id = "";
        this.house.name = this.house.id = "";
      },
      deep: true
    },
    building: {
      handler() {
        this.unit.name = this.unit.id = "";
        this.house.name = this.house.id = "";
      },
      deep: true
    },
    unit: {
      handler() {
        this.house.name = this.house.id = "";
      },
      deep: true
    }
  },
  created() {},
  methods: {
    togglePopup() {
      this.popupVisible = !this.popupVisible;
      if (this.popupType !== "houseType" && this.popupVisible) {
        this.searchResult = [];
        if (this.popupType === "community") {
          /* 小区 */
          this.searchKey = "";
          // if (this.searchKey) querySearchResult.call(this);
        } else {
          /* 楼栋|单元|户号 */
          this.buildingUnitResult = [];
          this.searchKey = "";
          this[this.popupType].name = this[this.popupType].id = "";
          this.$nextTick(() => {
            getBuildingUnit({
              cityCode: this.cityCode,
              communityID: this.community.id,
              buildingID: this.building.id,
              unitID: this.unit.id
            }).then(res => {
              if (res.respCode === "000000") {
                if (
                  !res.params ||
                  (Array.isArray(res.params) && res.params.length === 0)
                ) {
                  this.$toast({
                    message: "暂无数据",
                    position: "bottom",
                    duration: 2000
                  });
                  return;
                }
                this.buildingUnitResult = res.params;
                this.searchResult = matchSearchKey(
                  this.buildingUnitResult,
                  this.searchKey
                );
              }
            });
          });
        }
      }
    },
    setPopupType(type) {
      this.popupType = type;
      this.togglePopup();
    },
    onPickerValuesChange(picker, values) {},
    pickerConfirm() {
      if (this.popupType === "houseType") {
        this.houseType = this.$refs.picker.getValues()[0];
      }
      this.togglePopup();
    },
    searchResultClick(name, id, districtName) {
      this[this.popupType].name = name;
      this[this.popupType].id = id;
      districtName && (this.districtName = districtName);
      this.togglePopup();
    },
    /* 评估 */
    evaluate() {
      if (validSpecialChar(this.building.name)) {
        this.$messagebox.alert("请输入正确的楼栋号");
        return;
      }
      if (validSpecialChar(this.unit.name)) {
        this.$messagebox.alert("请输入正确的单元");
        return;
      }
      if (validSpecialChar(this.house.name)) {
        this.$messagebox.alert("请输入正确的门牌号");
        return;
      }
      if (Number(this.floor) > Number(this.totalFloor)) {
        this.$messagebox.alert("所在楼层大于总楼层数");
        return;
      }
      const data = {
        cityCode: this.cityCode,
        cityName: this.cityName,
        districtName: this.districtName,
        communityID: this.community.id,
        communityName: this.community.name,
        buildingArea: this.buildingArea,
        houseType: this.houseType,
        buildingID: this.building.id,
        buildingName: this.building.name,
        unitID: this.unit.id,
        unitName: this.unit.name,
        houseID: this.house.id,
        houseName: this.house.name,
        totalFloor: this.totalFloor,
        floor: this.floor
      };
      buildingEvaluate(data).then(res => {
        if (res.respCode === "000000" || res.respCode == "11510") {
          if (!window.sessionStorage.getItem("evaluateInfo")) {
            window.sessionStorage.setItem("evaluateInfo", "[]");
          }
          let evaluateInfo = JSON.parse(
            window.sessionStorage.getItem("evaluateInfo")
          );

          evaluateInfo.push({
            ...res.params,
            recordPropertySite: this.cityName + "/" + this.districtName, //房产所在地址
            recordPlotName: this.community.name, // 小区名称
            rectrdBuilding: this.building.name, // 楼栋号
            rectrdUnit: this.unit.name, //单元号
            rectrdHouseNumber: this.house.name, //门牌号
            rectrdType: this.houseType, //房屋类型
            rectrdArea: this.buildingArea, //建筑面积
            rectrdFloor: this.floor, //楼层
            rectrdCountFloor: this.totalFloor, //总楼层
            faileCode: res.respCode  // 评估失败错误码
          });

          window.sessionStorage.setItem(
            "evaluateInfo",
            JSON.stringify(evaluateInfo)
          );

          this.$router.replace({ name: "evaluate" });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
$color-border: #ccc;
$margin-lr: 0.15rem;
.app-main {
  .red-star {
    color: red;
    margin-right: .05rem;
  }
  .progress-bar {
    width: 100%;
    height: 0.48rem;
    display: flex;
    align-items: center;
    padding: 0 $margin-lr;
    border-bottom: 1px solid $color-border;
    img {
      width: 100%;
      height: 0.2rem;
    }
  }
  .input-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 0.45rem;
    padding: 0 $margin-lr;
    border-bottom: 1px solid $color-border;
    background-color: #fff;
    span.title {
      font-size: 0.15rem;
      color: #4d4d4d;
    }
    img.arrow {
      $w_h: 0.16rem;
      width: $w_h;
      height: $w_h;
    }
    /deep/ input {
      font-size: 0.15rem;
      text-align: right;
      padding-right: 0.1rem;
    }
    /deep/ .mint-cell-wrapper {
      padding-right: 0;
    }
  }
  .btns {
    margin: 0.3rem $margin-lr;
    height: 0.42rem;
    .btn-apply {
      width: 100%;
      height: 100%;
    }
  }
}
// 选择器工具条样式
@include pickerToolBar;
// 搜索页样式
.search-wrapper {
  width: 100%;
  height: 100vh;
  background-color: rgba(0,0,0,0.1);
  // padding: .5rem 0;
  $search-header: 0.75rem;
  $whiteColor:#fff;
  .search-header {
    display: flex;
    align-items: center;
    padding: 0.2rem .1rem;
    height: $search-header;
    background-color: $whiteColor;
    .input-box {
      flex: 1;
      height: 100%;
      display: flex;
      align-items: center;
      border: 1px solid #b8bbbf;
      border-radius: 0.04rem;
      padding: 0;
      .icon.search {
        width: 0.4rem;
        height: 100%;
        position: relative;
        &::after {
          $w_h: 0.14rem;
          content: "";
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          width: $w_h;
          height: $w_h;
          background-image: url("~@/assets/images/common/search.png");
          background-size: 100% 100%;
        }
      }
      .input {
        flex: 1;
        height: 100%;
        background-color: transparent;
        /deep/ input {
          font-size: 0.15rem;
          text-align: left;
        }
        /deep/ .mint-cell-wrapper {
          padding: 0;
        }
      }
    }
    button {
      height: 100%;
      width: 0.5rem;
      font-size: 0.13rem;
    }
  }
  .search-content {
    height: calc(100% - #{$search-header});
    overflow: auto;
    -webkit-overflow-scrolling: touch;
    background-color: $whiteColor;

    ul li {
      display: flex;
      height: 0.3rem;
      font-size: 0.14rem;
      color: #333;
      padding: 0 0.1rem;
      align-items: center;
      justify-content: center;
      &.between {
        justify-content: space-between;
      }
      border-bottom: 1px solid #ccc;
    }
  }
}
</style>
